<template>
  <div class="chart_container" v-if="currentList && currentList.length">
    <template v-for="code in currentList" :key="code">
      <template v-for="item in channel" :key="item">
        <div :class="['box', item, code.replaceAll('.', '')]"></div>
      </template>
    </template>
  </div>
  <div class="chart_container empty" v-else>
    <Empty :image="simpleImage"></Empty>
  </div>
</template>

<script setup lang="tsx">
import { computed, inject, nextTick, ref, watch } from 'vue';
import { Empty, message } from 'ant-design-vue';
import * as echarts from 'echarts';
import 'echarts/theme/macarons';

const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;
const props = defineProps({
  channel: {
    type: Array,
    default: [],
  },
  presentation: {
    type: Array,
    default: [],
  },
  deviceInfo: {
    type: Array,
    default: [],
  },
  data: {
    type: Object,
    default: () => {},
  },
  formatSignal: {
    type: null,
  },
  queryParams: {
    type: Object,
    default: () => {},
  },
});
const devices = ref([]);
const currentList = computed(() => {
  const asyncKeys = Object.keys(dataInfo.value['result1'] || {});

  return devices.value.filter((i) => asyncKeys.includes(i.replaceAll('.', '')));
});
watch(
  () => props,
  (val) => {
    // 通道
    nextTick(() => {
      console.log('触发');

      if (!Object.keys(val.data).length) return;
      dataInfo.value = val.data;
      getInfo(val.channel, val.presentation[0], val.deviceInfo);
    });
  },
  { deep: true, immediate: true },
);
const { formatSignal } = props;
const dataInfo = ref(props.data);
const processFn = (code, node, data, type, channel) => {
  if (formatSignal && typeof formatSignal === 'function')
    return formatSignal(code, node, data, type, channel);
  const [data1, data2] = data;
  const i = data1[0].i;
  const text =
    [code, i, channel].join('.') +
    ' - 信噪比[幅值' +
    (type == 'log' ? 'log' : '') +
    '(cm/s/s)---频率(Hz)]';
  const seriesData1 = data1.map((i) => {
    if (i.xf == 0) return;
    return [i.xf, Number(i.g?.toFixed(6))];
  });
  const seriesData2 = data2.map((i) => {
    if (i.xf == 0) return;
    return [i.xf, Number(i.g?.toFixed(6))];
  });
  return { text, node, seriesData1, seriesData2, type };
};
const getInfo = (channelList, type, deviceList) => {
  console.log(channelList, type, deviceList, '2');

  devices.value = deviceList;
  const { result1, result2 } = dataInfo.value;
  for (const code in result1) {
    const keys = deviceList.map((i) => i.replaceAll('.', ''));
    if (!keys.includes(code)) return;
    channelList.forEach((channel) => {
      nextTick(() => {
        const nodes = document.querySelectorAll(
          `.${channel}.${code.replaceAll('.', '')}`,
        );
        nodes.forEach((node) => {
          const result = processFn(
            code,
            node,
            [
              result1[code][conversion(channel)],
              result2[code][conversion(channel)],
            ],
            type,
            channel,
          );
          init(result);
        });
      });
    });
  }
};
const init = ({ text, node, seriesData1, seriesData2, type }) => {
  const chart = echarts.init(node);
  const option = {
    title: {
      text,
      textStyle: {
        color: '#fff',
        fontSize: 14,
      },
      top: '4%',
      left: '4%',
    },
    grid: [
      {
        top: '25%',
        bottom: '25%',
        right: '3%',
        left: '4%',
        show: true,
      },
    ],
    legend: {
      data: ['触发数据', '噪声数据'],
      top: '10',
      right: '5%',
      textStyle: {
        color: '#fff',
        fontSize: 14,
      },
    },
    color: ['#EE6666', '#95CE7A'],
    xAxis: [
      {
        show: true,
        type: type,
        splitLine: {
          show: false,
          lineStyle: {
            type: 'dashed',
          },
        },
        axisLine: {
          show: false,
          onZero: false,
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          show: true,
          color: '#fff',
          showMaxLabel: true,
        },
        max: function (value) {
          return value.max;
        },
      },
    ],
    yAxis: [
      {
        type: type,
        splitLine: {
          show: false,
          lineStyle: {
            type: 'dashed',
          },
        },
        axisLine: {
          show: false,
          onZero: false,
        },
        axisLabel: {
          color: '#fff',
          fontSize: '12px',
          formatter: function (params) {
            return type == 'value' ? params : Math.log10(params);
          },
        },
        axisTick: {
          show: false,
        },
      },
    ],
    dataZoom: {
      show: false,
      type: 'inside',
      filterMode: 'none',
      start: 0,
      end: 100,
    },
    series: [
      {
        datasetIndex: 1,
        type: 'line',
        data: seriesData1,
        name: '噪声数据',
        showSymbol: false,
        markPoint: {
          symbol: 'pin',
          symbolSize: 30,
          itemStyle: {
            color: 'blue',
          },
          data: [
            {
              name: '最大值',
              type: 'max',
              label: {
                formatter: function (params) {
                  return type == 'value'
                    ? params.data.value
                    : Math.log10(params.data.value).toFixed(6);
                },
              },
            },
            {
              name: '最大值',
              type: 'min',
              label: {
                formatter: function (params) {
                  return type == 'value'
                    ? params.data.value
                    : Math.log10(params.data.value).toFixed(6);
                },
              },
            },
          ],
        },
        // animationDurationUpdate: 1000,
        lineStyle: {
          color: '#95CE7A',
          //设置线条默认样式
          normal: {
            width: 1,
          },
          //设置线条hover样式
          emphasis: { width: 1 },
        },
      },
      {
        data: seriesData2,
        name: '触发数据',
        datasetIndex: 0,
        type: 'line',
        showSymbol: false,
        markPoint: {
          symbol: 'pin',
          symbolSize: 30,
          itemStyle: {
            color: 'red',
          },
          data: [
            {
              name: '最大值',
              type: 'max',
              label: {
                formatter: function (params) {
                  return type == 'value'
                    ? params.data.value
                    : Math.log10(params.data.value).toFixed(6);
                },
              },
            },
            {
              name: '最大值',
              type: 'min',
              label: {
                formatter: function (params) {
                  return type == 'value'
                    ? params.data.value
                    : Math.log10(params.data.value).toFixed(6);
                },
              },
            },
          ],
        },
        // animationDurationUpdate: 1000,
        lineStyle: {
          color: '#EE6666',
          //设置线条默认样式
          normal: {
            width: 1,
          },
          //设置线条hover样式
          emphasis: { width: 1 },
        },
      },
    ],
    animationDurationUpdate: 500,
  };
  chart.setOption(option);
  addEventListener('resize', function () {
    chart.resize();
  });
};

const conversion = (num) => {
  switch (num) {
    case 'EIZ':
      return 'a';
    case 'EIN':
      return 'b';
    case 'EIE':
      return 'c';
  }
};
</script>

<style lang="scss" scoped>
.chart_container {
  width: 100%;
  // height: 100%;
  display: grid;
  grid-template-rows: repeat(3, 1fr);
  gap: 1vh;
  .box {
    height: 25vh;
  }
  &.empty {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
